package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.pojo.Cart;
import com.qf.utils.DBTools;
import com.qf.utils.SQL;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    QueryRunner qr=new QueryRunner(DBTools.getDataSource());

    @Override
    public int insertCart(Cart cart) {
        String sql="insert into cart VALUES (null,?,?,?,?,?)";
        try {
            qr.update(sql,cart.getGid(),cart.getUid(),cart.getGname(),cart.getPrice() ,cart.getNum());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public List<Cart> selectAll(Integer uid) {
        BeanListHandler<Cart> bean=new BeanListHandler(Cart.class);
        //String CART=" cart_id  cartid, g_id  gid,u_id  uid,cart_gname gname,cart_gprice price,cart_num num  ";
        String sql="SELECT "+ SQL.CART +"FROM CART WHERE U_ID=?";
        try {
            return qr.query(sql,bean,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Cart selectOne(Integer uid, Integer gid) {
        Connection c= DBTools.getConnection();//有事务。要用统一的连接；
        BeanHandler <Cart> bean=new BeanHandler(Cart.class);
        String sql="SELECT "+ SQL.CART +"FROM CART WHERE U_ID=? AND G_ID=?";
            try {
            return qr.query(c,sql,bean,uid,gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
            return null;
    }

    @Override
    public int updateOne(Integer uid, Integer gid, int num) {
        String sql="UPDATE cart SET cart_num = ? WHERE u_id=? and g_id=?;";
        try {
            return qr.update(sql,num,uid,gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    //购物车中删除一项
    @Override
    public int deleteOne(Integer uid, Integer gid) {
        String sql="DELETE FROM CART  WHERE u_id=? AND g_id=?";
        Connection c= DBTools.getConnection();//有事务。要用统一的连接；
        try {
            return qr.update(c,sql,uid,gid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
